<?php

namespace app\admin\controller\finance;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\Config;
use app\admin\model\Middleman;
use app\admin\model\ShopFollow;
use app\admin\model\ShopPlatform;
use app\admin\model\Admin;
use app\admin\model\Play;
use app\common\model\OrderProof;
use app\common\model\Order;

/**
 * 店铺管理
 *
 */
class Bill extends Backend
{
    /**
     * Play模型对象
     * @var \app\admin\model\Play
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        // $this->model = new \app\admin\model\Play;
        $this->model = new \app\admin\model\Shop;
        $salesmanList = [];
        $salesman = $this->salesmanList();
        foreach ($salesman as $key => $value) {
            $salesmanList[$value['id']] = $value['nickname'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
         // Db::connect(config('database.db2'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // 有已完成的活动订单
            $filter = $_GET['filter'];
            $filterarr = [];
            if ($filter) {
                $filterarr = json_decode($filter,1);
            }
            $bill_list = Db::name('bill_list')->order('id DESC')->find();
            if (!$bill_list) {
                $where2 = '1=1';
            } else {
                $where2 = 'bl.create_dt="'.$bill_list['create_dt'].'"';
            }
            // $where2 = '1=1';
            // if (isset($filterarr['id'])) {
            //     $where2 .= ' and bl.shop_id='.$filterarr['id'];
            // }
            // if (isset($filterarr['shop_no'])) {
            //     $where2 .= ' and bl.shop_no like "%'.$filterarr['shop_no'].'%"';
            // }
            if (isset($filterarr['user_id'])) {
                $where2 .= ' and bl.user_id='.$filterarr['user_id'];
            }
            if (isset($filterarr['shop_name'])) {
                $where2 .= ' and bl.shop_name like "%'.$filterarr['shop_name'].'%"';
            }
            if (isset($filterarr['pay_status'])) {
                if ($filterarr['pay_status']==0) {
                    $where2 .= ' and bl.pay_status="待支付"';
                } elseif ($filterarr['pay_status']=1) {
                    $where2 .= ' and bl.pay_status=""';
                }
            }
            if (isset($filterarr['service_admin_by'])) {
                $where2 .= ' and bl.service_admin_id='.$filterarr['service_admin_by'];
            }
            if (isset($filterarr['shop_area'])) {
                $where2 .= ' and bl.shop_area like "%'.$filterarr['shop_area'].'%"';
            }
            if (isset($filterarr['phone'])) {
                $where2 .= ' and s.phone like "%'.$filterarr['phone'].'%"';
            }
            if (isset($filterarr['nickname'])) {
                $where2 .= ' and u.nickname like "%'.$filterarr['nickname'].'%"';
            }
            if (isset($filterarr['last_pay_time'])) {
                $date = explode(' - ', $filterarr['last_pay_time']);
                $where2 .= ' and bl.last_pay_time >'.strtotime($date[0]).' and last_pay_time<'.strtotime($date[1]);
            }
            if (isset($filterarr['nopay_dt'])) {
                $date = explode(' - ', $filterarr['nopay_dt']);
                $where2 .= ' and bl.nopay_dt >"'.$date[0].'" and nopay_dt<"'.$date[1].'"';
            }
            if (isset($filterarr['play_status'])) {
                if ($filterarr['play_status']==1) {
                    $where2 .= ' and bl.play_status like "%正常%"';
                } elseif ($filterarr['play_status']==2) {
                    $where2 .= ' and bl.play_status like "%紧急账单%"';
                } elseif ($filterarr['play_status']==3) {
                    $where2 .= ' and bl.play_status like "%异常账单%"';
                } elseif ($filterarr['play_status']==4) {
                    $where2 .= ' and bl.play_status like "%大额账单%"';
                }
            }
            // 权限
            $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
            $explode = explode(',', $auth_group_access);
            if (in_array(5,$explode)) {
                $member = Db::name('admin')->where('leader',$this->auth->id)->value('group_concat(id)');
                $access_user = explode(',', $member);
                $access_user[] = $this->auth->id;
                $implode = implode(',', $access_user);
                $where2 .= ' and bl.service_admin_id in ('.$implode.')';
            } elseif (in_array(3,$explode)) {// 业务员
                $where2 .= ' and bl.service_admin_id='.$this->auth->id;
            }
            $data = Db::name('bill_list')->alias('bl')
                ->join('chbc_shop s','s.id=bl.shop_id','left')
                ->join('chbc_user u','u.id=(bl.user_id-'.config('virtual_userid').')','left')
                ->where($where2)
                ->field('bl.*,u.nickname,s.phone')
                ->order('bl.id DESC,bl.user_id ASC,bl.shop_id DESC')
                ->paginate($limit);
            $list = [];
            foreach ($data as $key => $row) {
                $list[$key] = $row;
                $play = Db::name('play_order')->field('create_dt')->where('order_status in (3,6,-9) and shop_no='.$row['shop_no'].' and is_pay=0')->order('create_dt asc')->find();
                if ($row['nopay_dt']=='1970-01-01 00:00:00') {
                    $list[$key]['nopay_dt'] = '';
                }
            }
            foreach ($list as &$value) {
                $value['id'] = $value['shop_id'];
                $value['total_money'] = $value['total_money']==0?'':$value['total_money'].'元';
            }
            $result = array("total" => $data->total(), "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function add($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $shop_no = input('ids','');// 店铺编号
            // $shop = Db::name('shop')->where(['shop_no'=>$shop_no])->field('have_uid')->find();
            // $shop_no = Db::name('shop')->where('have_uid',$shop['have_uid'])->value('group_concat(shop_no)');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!$shop_no) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $filter = $_GET['filter'];
            $filterarr = [];
            if ($filter) {
                $filterarr = json_decode($filter,1);
            }
            $where2 = 'order.shop_no='.$shop_no;
            if (isset($filterarr['update_dt'])) {
                $arr = explode(' - ', $filterarr['update_dt']);
                $where2 .= ' and opi.update_dt>"'.$arr[0].'" and opi.update_dt<"'.$arr[1].'"';
            }
            if (isset($filterarr['id'])) {
                $where2 .= ' and order.id='.$filterarr['id'];
            }
            $model = new Order();
            $list = $model->alias('order')
                ->join('chbc_order_pay_item opi','opi.play_order_no=order.play_order_no')
                ->join('chbc_order_pay op','opi.pay_no=op.pay_no and op.pay_status=1')
                ->field('order.*,op.update_dt,opi.pay_no,op.pay_mod,op.tran_no')
                ->where($where)
                ->where($where2)
                ->order('order.id DESC')
                ->paginate($limit);
            $data = [];
            foreach ($list as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['play_order_no'] = $v['play_order_no'];
                $data[$k]['shop_name'] = $v['shop_name'];
                $data[$k]['start_date_text'] = $v['create_dt'];
                $data[$k]['sum'] = $v['service_charge_amt']+$v['actual_rebate_amt'];
                $data[$k]['pay_mod'] = $v['pay_mod']=='alipay'?'支付宝':'微信';
                $data[$k]['tran_no'] = $v['tran_no'];
                $data[$k]['update_dt'] = strtotime($v['update_dt']);
            }

            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['shop_no']);
        $this->view->assign("shop_name", $row['shop_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $shop_no = input('ids','');// 店铺编号
            // $shop = Db::name('shop')->where(['shop_no'=>$shop_no])->field('have_uid')->find();
            // $shop_no = Db::name('shop')->where('have_uid',$shop['have_uid'])->value('group_concat(shop_no)');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!$shop_no) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }

            $model = new Order();
            $list = $model
                ->field('*')
                ->where($where)
                ->where('shop_no='.$shop_no.' and is_transfer=1')
                ->order('id DESC')
                ->paginate($limit);
            $data = [];
            foreach ($list as $k => $v) {
                $like = ','.$v['id'].',';
                $bill_log = Db::name('bill_log')->where('play_ids like "%'.$like.'%"')->find();
                $submit_by = Db::name('admin')->where(['id'=>$bill_log['submit_by']])->value('nickname');
                $data[$k]['id'] = $v['id'];
                $data[$k]['play_order_no'] = $v['play_order_no'];
                $data[$k]['shop_name'] = $v['shop_name'];
                $data[$k]['start_date_text'] = $v['create_dt'];
                $data[$k]['sum'] = $v['service_charge_amt']+$v['actual_rebate_amt'];
                $data[$k]['update_dt'] = strtotime($bill_log['update_dt']);
                $data[$k]['submit_by'] = $submit_by?$submit_by:'';
                $data[$k]['img'] = config('upload_domain').$bill_log['img'];
            }

            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['shop_no']);
        $this->view->assign("shop_name", $row['shop_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }


    public function bill($ids = null)
    {
        $model = new \app\admin\model\Shop();
        $row = $model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $url = config('bill_domain') . '/?bill='.$row['shop_no'];
        $qrcode = (new \app\admin\controller\shops\Shop())->billQrcode($row['shop_no'],2,$url);
        // 改成商家关联的店铺
        $shops = Db::name('user')->alias('u')->join('chbc_shop s','s.shop_no=u.shop_no')->field('s.*')->where(['u.id'=>$row['have_uid']])->find();
        if (!$shops) $shops = $row;
        $this->view->assign("shops", $shops);
        $this->view->assign("row", $row);
        $this->view->assign("qrcode", $qrcode);
        $this->view->assign("url", $url);
        return $this->view->fetch();
    }

    public function item()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $shop_no = input('ids','');// 店铺编号
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!$shop_no) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $list = Db::name('play_order')->alias('order')
                ->where($where)
                ->field('order.*,s.shop_type')
                ->join('chbc_shop s','s.shop_no=order.shop_no','left')
                ->where('order.shop_no="'.$shop_no.'" and order.order_status in (3,6,-9) and order.create_dt<"'.date('Y-m-d').'"')
                ->order('order.is_pay asc,order.id desc')
                ->paginate($limit);
            $list2 = $list->items();
            $Shop2 = new \app\admin\model\Shop();
            $OrderProof2 = new \app\common\model\OrderProof();
            foreach ($list2 as $k => &$v) {
                $upload_domain = config('upload_domain');
                $v['proof'] = $OrderProof2->where('play_order_no',$v['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,actual_pay')->find();
                if ($v['cps_id']>0) {
                    $v['proof']['one_image'] = '';
                } else {
                    $v['proof']['one_image'] = strpos($v['proof']['one_image'],'://')===false?$upload_domain.$v['proof']['one_image']:$v['proof']['one_image'];
                }
                if ($v['proof']['two_image']) {
                    $v['proof']['two_image'] = strpos($v['proof']['two_image'],'://')===false?$upload_domain.$v['proof']['two_image']:$v['proof']['two_image'];
                } else {
                    $v['proof']['two_image'] = '';
                }
                if ($v['proof']['three_image']) {
                    $v['proof']['three_image'] = strpos($v['proof']['three_image'],'://')===false?$upload_domain.$v['proof']['three_image']:$v['proof']['three_image'];
                } else {
                    $v['proof']['three_image'] = '';
                }
                $v['rebate_amt'] = round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
                $v['shop'] = [];
                $v['shop']['shop_type_text'] = $Shop2->getShopTypeTextAttr($v['shop_type'],$v);
                $v['shop']['shop_name'] = $v['shop_name'];
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['shop_no']);
        $this->view->assign("shop_name", $row['shop_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }

    public function sjitem()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $uid = input('ids','');// 店铺编号
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!$uid) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $shops = Db::name('shop')->where(['have_uid'=>$uid,'shop_status'=>1])->field('shop_no')->select();
            $shop_no = '';
            foreach ($shops as $key => $value) {
                $shop_no .= $value['shop_no'].',';
            }
            $shop_no = trim($shop_no,',');
            $list = Db::name('play_order')->alias('order')
                ->where($where)
                ->field('order.*,s.shop_type')
                ->join('chbc_shop s','s.shop_no=order.shop_no','left')
                ->where('order.shop_no in ('.$shop_no.') and order.order_status in (3,6,-9) and order.create_dt<"'.date('Y-m-d').'"')
                ->order('order.is_pay asc,order.id desc')
                ->paginate($limit);
            $list2 = $list->items();
            $Shop = new \app\admin\model\Shop();
            $OrderProof = new \app\common\model\OrderProof();
            foreach ($list2 as $k => &$v) {
                $upload_domain = config('upload_domain');
                $v['proof'] = $OrderProof->where('play_order_no',$v['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,actual_pay')->find();
                if ($v['cps_id']>0) {
                    $v['proof']['one_image'] = '';
                } else {
                    $v['proof']['one_image'] = strpos($v['proof']['one_image'],'://')===false?$upload_domain.$v['proof']['one_image']:$v['proof']['one_image'];
                }
                if ($v['proof']['two_image']) {
                    $v['proof']['two_image'] = strpos($v['proof']['two_image'],'://')===false?$upload_domain.$v['proof']['two_image']:$v['proof']['two_image'];
                } else {
                    $v['proof']['two_image'] = '';
                }
                if ($v['proof']['three_image']) {
                    $v['proof']['three_image'] = strpos($v['proof']['three_image'],'://')===false?$upload_domain.$v['proof']['three_image']:$v['proof']['three_image'];
                } else {
                    $v['proof']['three_image'] = '';
                }
                $v['rebate_amt'] = round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
                $v['shop'] = [];
                $v['shop']['shop_type_text'] = $Shop->getShopTypeTextAttr($v['shop_type'],$v);
                $v['shop']['shop_name'] = $v['shop_name'];
                if ($v['shop']['shop_type_text']=='饿了么') $v['proof']['actual_pay'] = '-';
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['have_uid']);
        $this->view->assign("shop_name", $row['shop_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }

    /**
     * 线下转账
     * @DateTime 2023-05-02T13:31:14+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    public function transfer($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $play_id = $this->request->post("btSelectItem/a");
            if (!$play_id) $this->error('请选择订单');
            $time = time();
            if ($params) {
                Db::startTrans();
                // try {
                    $play_order = Db::name('play_order')->field('id,shop_no,play_order_no,service_charge_amt,actual_rebate_amt,is_fushen,user_id,order_status,shop_name')->where(['id'=>['in',$play_id],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->select();
                    if (!$play_order) $this->error('订单数据有误');
                    $sum = 0;
                    foreach ($play_order as $key => $value) {
                        $sum += round($value['service_charge_amt']+$value['actual_rebate_amt'],2);
                    }
                    Db::name('play_order')->where(['id'=>['in',$play_id],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->update(['order_status'=>3,'is_pay'=>1,'pay_time'=>$time,'is_transfer'=>1]);
                    Db::name('bill_log')->insert([
                        'shop_no' => $params['shop_no'],
                        'type' => '线下转账',
                        'img' => $params['img'],
                        'submit_by' => $this->auth->id,
                        'play_ids' => ','.implode(',', $play_id).','
                    ]);
                    // 更新商家账单
                    $bill_list = Db::name('bill_list')->order('id DESC')->find();
                    $where = 'create_dt="'.$bill_list['create_dt'].'" and shop_no='.$params['shop_no'];
                    $bill_list = Db::name('bill_list')->where($where)->field('*')->find();
                    if ($bill_list) {
                        $update = [];
                        $play_status = '正常';
                        $last_pay_time = $time;// 到账时间
                        $play = Db::name('play_order')->where('order_status in (3,-9) and shop_no='.$params['shop_no'].' and is_pay=0')->where('create_dt<"'.date('Y-m-d H:i:s',$time-259200).'"')->count();
                        if ($play) {
                            $play_status = '紧急账单';
                        }
                        $play = Db::name('play_order')->where('order_status in (3,-9) and shop_no='.$params['shop_no'].' and is_pay=0')->where('create_dt<"'.date('Y-m-d H:i:s',$time-777600).'"')->count();
                        if ($play) {
                            $play_status = '异常账单';
                        }
                        $sum = $bill_list['total_money']-$sum;
                        $update['last_pay_time'] = 0;
                        $update['total_money'] = 0;
                        $update['pay_status'] = '';
                        $update['nopay_dt'] = '1970-01-01 00:00:00';
                        if ($sum>0) {
                            $update['pay_status'] = '待支付';
                            $update['total_money'] = round($sum,2);
                            $order = Db::name('play_order')->field('create_dt')->where(['shop_no'=>$params['shop_no']])->where('is_pay=0 and order_status in (3,6,-9) and create_dt<"'.substr($bill_list['create_dt'], 0,10).'"')->order('create_dt asc')->find();
                            if ($order) {
                                $update['nopay_dt'] = $order['create_dt'];
                            }
                        } else {
                            $update['pay_status'] = '已支付';
                            $update['last_pay_time'] = $last_pay_time;
                        }
                        $update['play_status'] = $play_status;
                        $update['update_dt'] = date('Y-m-d H:i:s',time());
                        Db::name('bill_list')->where('id='.$bill_list['id'])->update($update);
                    }
                    Db::commit();
                // } catch (Exception $e) {
                //     Db::rollback();
                //     $this->error('处理失败');
                // }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        // $shop_no = Db::name('shop')->where('have_uid',$row['have_uid'])->value('group_concat(shop_no)');
        
        $order = (new Order())->where(['order_status'=>['in',[3,6,-9]],'is_pay'=>0])->where('shop_no='.$row['shop_no'].' and create_dt<"'.date('Y-m-d').'"')->order('id DESC')->select();
        foreach ($order as $key => &$value) {
            $value['sum'] = $value['service_charge_amt']+$value['actual_rebate_amt'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("order", $order);
        return $this->view->fetch();
    }


    /**
     * 标记为坏账
     * @DateTime 2023-05-02T13:27:43+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    public function baddebt($ids = null)
    {
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        Db::name('bill_log')->insert([
            'shop_no' => $row['shop_no'],
            'type' => '标记为坏账',
            'submit_by' => $this->auth->id
        ]);
        $this->success();
    }


    /**
     * 标记为正常
     * @DateTime 2023-05-02T13:27:43+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    public function normaldebt($ids = null)
    {
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        Db::name('bill_log')->insert([
            'shop_no' => $row['shop_no'],
            'type' => '恢复正常',
            'submit_by' => $this->auth->id
        ]);
        $this->success();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        // 状态参数过滤掉
        if (isset($filter['update_dt'])) {
            unset($filter['update_dt']);
        }
        if (isset($filter['id'])) {
            unset($filter['id']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


    public function order()
    {
        $shop_no = input('shop_no',0);// 活动id
        $date = input('date','');
        $arr = explode(' - ', $date);
        if (count($arr)!=2) {
            $this->error('日期格式有误');
        }
        $sum=0;
        $order = (new Order())->where(['order_status'=>['in',[3,6,-9]],'is_pay'=>0])->where('shop_no='.$shop_no.' and create_dt<"'.$arr[1].'" and create_dt>="'.$arr[0].'"')->order('id DESC')->select();
        foreach ($order as $key => &$value) {
            $value['sum'] = $value['service_charge_amt']+$value['actual_rebate_amt'];
            $sum+=$value['sum'];
        }
        $this->success('succ',null,['order'=>$order,'sum'=>round($sum,2)]);
    }


}
